'use strict'
const titbit = require('titbit');
const fs = require('fs');

const pg = require('pg');
const { request } = require('https');
const wxkey = require('./wxkey');
const {httpcli} = require('gohttp');
const token = require('titbit-token');
const tbloader = require('titbit-loader')
const dbcfg = require('./dbconfig');
process.chdir(__dirname);

try {
    fs.accessSync('/home/images');
} catch (err) {
    fs.mkdirSync('/home/images');
}

let cert_path = '/usr/local/share';
const app = new titbit({
    debug : true,
    globalLog:true,
    timeout: 60000,
    server: {
        handshakeTimeout: 35000
    },
    cert: `${cert_path}/api.hiehie.top.pem`,
    key:`${cert_path}/api.hiehie.top.key`
})
app.use(async (c , next) => { // 设置不校验域名
    let method = ['GET','POST','PUT','DELETE','OPTIONS'];
    c.setHeader('Access-Control-Allow-Origin','*');
    c.setHeader('Access-Control-Allow-Methods',method);
    c.setHeader('Access-Control-Allow-Headers',['content-type','update','authorization','x-requested-with']);
    await next();
})

let psql = new pg.Pool(dbcfg);//启用数据库

let tb = new tbloader();
tb.init(app);

app.addService('psql',psql);//将数据库添加至service对象中
app.addService('imagePath',`/home/images`)// 保存设计的目录
let tok = new token({
    expires:9999,//有效期为9999秒
    key:'watashidaisukikasumigaokautahaha',

    iv:'tenshisamakekkon'
});
app.options('/*',async c => {})
app.get("/",async c => {
    c.send("Kasumigaoka Utaha")
});
app.addService('tok',tok);
app.post('/login/:code',async c => {// 用户登录后获取其openid等信息并将其加密为token发送给用户并验证如果是新用户则创建新用户
    let reqForInfo_url = 'https://api.weixin.qq.com/sns/jscode2session' // 用户登录后获取其openid等信息并将其加密为token发送给用户
                        +`?appid=${wxkey.appid}`
                        +`&secret=${wxkey.secret}`
                        +`&js_code=${c.param.code}`
                        +`&grant_type=authorization_code`;
    let r = await httpcli.get(reqForInfo_url)
                        .then(res => res.json());
    console.log(r);
    
    if (!r.errcode) {  // 成功获得信息后并验证如果是新用户则创建新用户
        try {
            let sqltext = `SELECT * FROM users WHERE "openId"=$1`;
            let ret =await c.service.psql.query(sqltext , [r.openid]);
            console.log('ret',ret.rows)
            console.log('执行了1')
            console.log(ret.rows == "[]")
            console.log(ret.rows == [])
            console.log(typeof ret.rows)
            
            console.log(ret.rows.length)
            if (ret.rows.length == 0) { //未在用户数据库查询到数据，为新用户，创建新用户   //目前无法正确添加数据库，原因是无法走这一分支，待测试
                console.log('执行了2')
                let sqlCreateUser = `INSERT INTO `
                                    +`users("openId","userInfo","userDay")`
                                    +`VALUES ($1,$2,$3)`;

                console.log('print c.body!!!!!',c.body)
                let user = c.body //此处最好打印一下c.body看一下数据的结构

                let rt = await c.service.psql.query(sqlCreateUser,[r.openid,user,new Date().getTime()]);
                let rs = await c.service.psql.query(sqltext , [r.openid]); // 插入后查询新插入的用户，获得其用户信息
                console.log('rs',rs.rows[0])
                c.send(tok.make(rs.rows[0])); //
                
            }else{
                console.log('ret',ret.rows[0])
                c.send(tok.make(ret.rows[0])); //
            }
        } catch (err) {
            c.status(500).send("Database's operations failed!")
        }
    }
    else{ //获取信息失败（登录失败）
        c.status(502).send("Data Get Failed!")
    }
    
})
app.get('/decrypt/:token',async c=> {
    c.send(tok.verify(c.param.token));
})


app.run(2344);